﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;
using System.Text.RegularExpressions;
namespace Presentation
{
    public partial class frmQuanLyKhachHang : DevComponents.DotNetBar.Office2007Form
    {
        DataView dv = new DataView();
        DataTable dt = new DataTable();
        bool save;
        private bool isFormClosing = false;
        // Contant for the close message
        private const int WM_CLOSE = 16;
        //override the WndProc msg to trap the WM_CLOSE message
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_CLOSE)
                isFormClosing = true;
            base.WndProc(ref m);
        }
        public frmQuanLyKhachHang()
        {
            InitializeComponent();
            dgvKhachHang.AutoGenerateColumns = false;
        }

        private void frmQuanLyKhachHang_Load(object sender, EventArgs e)
        {
            LoadGridView();
            save = false;
        }
        private void LoadGridView()
        {
            dt = KhachHangService.GetKhachHangTable(); ;
            dt.TableName = "KhachHang";
            dt.AcceptChanges();
            dv.Table = dt;
            dgvKhachHang.DataSource = dt;
            btnCapNhat.Enabled = true;
            dgvKhachHang.ReadOnly = false;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvKhachHang_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (isFormClosing)
                return;
            if (e.RowIndex == dgvKhachHang.RowCount - 1)
                return;
            if (e.FormattedValue.ToString() == "")
            {
                MessageBoxEx.Show("Không được bỏ trống!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            if (dgvKhachHang.Columns[e.ColumnIndex].Name == "DienThoai")
            {
                long sdt = 0;
                if (!long.TryParse(e.FormattedValue.ToString(), out sdt))
                {
                    MessageBoxEx.Show("Số điện thoại phải là số!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
            }
            if (dgvKhachHang.Columns[e.ColumnIndex].Name == "Email")
            {
                string email = e.FormattedValue.ToString();
                string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" +
               @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" +
               @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
                System.Text.RegularExpressions.Match match =Regex.Match(email.Trim(), pattern, RegexOptions.IgnoreCase);

                if (!match.Success)
                {
                    MessageBoxEx.Show("Nhập email không đúng định dạng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
                
            }
        }

        private int GetID()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            int id = -1;
            if (dtThem.Rows.Count == 0)
            {
                id = KhachHangService.GetCurrentID();

            }
            else
            {
                id = (int)dtThem.Rows[dtThem.Rows.Count - 1]["MaKhachHang"];

            }
            return id + 1;
        }
        private void dgvKhachHang_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = GetID();
            for (int i = e.Row.Index - 1; i < dgvKhachHang.RowCount-1; i++)
            {
                dgvKhachHang["MaKhachHang", i].Value = id++;
                dgvKhachHang["TienNo", i].Value = 0;                
            }
        }

        private void dgvKhachHang_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {

            if (isFormClosing)
                return;
            if (e.RowIndex == dgvKhachHang.RowCount - 1)
                return;
            for (int i = 0; i < dgvKhachHang.ColumnCount; i++)
            {
                if (dgvKhachHang[i, e.RowIndex].EditedFormattedValue.ToString() == "")
                {
                    dgvKhachHang.CurrentCell = dgvKhachHang[i, e.RowIndex];
                    dgvKhachHang.CurrentCell.Style.BackColor = Color.Red;
                    dgvKhachHang.CurrentCell.Style.ForeColor = Color.White;
                    dgvKhachHang.BeginEdit(true);
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void dgvKhachHang_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            dgvKhachHang[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
            dgvKhachHang[e.ColumnIndex, e.RowIndex].Style.ForeColor = Color.Black;
        }

        private void dgvKhachHang_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            int maKhachHang = int.Parse(e.Row.Cells["MaKhachHang"].FormattedValue.ToString());
            if (maKhachHang > KhachHangService.GetCurrentID())
            {
                for (int i = e.Row.Index + 1; i < dgvKhachHang.RowCount; i++)
                {
                    dgvKhachHang["MaKhachHang", i].Value = maKhachHang++;
                }

            }
        }

        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();


            List<KhachHangDTO> listThem = new List<KhachHangDTO>();
            for (int i = 0; i < dtThem.Rows.Count; i++)
            {
                string  hoTen, diaChi, dienThoai, email, tienNo;
                int maKhachHang;
                double d_TienNo;
                long l_DienThoai;
                maKhachHang = int.Parse(dtThem.Rows[i]["MaKhachHang"].ToString());
                hoTen = dtThem.Rows[i]["HoTen"].ToString();
                diaChi = dtThem.Rows[i]["DiaChi"].ToString();
                dienThoai = dtThem.Rows[i]["DienThoai"].ToString();
                email=dtThem.Rows[i]["Email"].ToString();
                tienNo = dtThem.Rows[i]["TienNo"].ToString();

                if (hoTen == "" || diaChi == "" || !long.TryParse(dienThoai, out l_DienThoai)
                    || email == "" || !double.TryParse(tienNo, out d_TienNo))
                    return false;
                
                KhachHangDTO kh = new KhachHangDTO();
                kh.MaKhachHang = maKhachHang;
                kh.HoTen =hoTen;
                kh.DiaChi = diaChi;
                kh.DienThoai = dienThoai;
                kh.Email = email;
                kh.TienNo = d_TienNo;
                kh.TinhTrang = 1;
                listThem.Add(kh);
            }

            List<KhachHangDTO> listCapNhat = new List<KhachHangDTO>();
            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {

                string hoTen, diaChi, dienThoai, email, tienNo;
                int maKhachHang;
                double d_TienNo;
                long l_DienThoai;
                maKhachHang = int.Parse(dtCapNhat.Rows[i]["MaKhachHang"].ToString());
                hoTen = dtCapNhat.Rows[i]["HoTen"].ToString();
                diaChi = dtCapNhat.Rows[i]["DiaChi"].ToString();
                dienThoai = dtCapNhat.Rows[i]["DienThoai"].ToString();
                email = dtCapNhat.Rows[i]["Email"].ToString();
                tienNo = dtCapNhat.Rows[i]["TienNo"].ToString();

                if (hoTen == "" || diaChi == "" || !long.TryParse(dienThoai, out l_DienThoai)
                    || email == "" || !double.TryParse(tienNo, out d_TienNo))
                    return false;

                KhachHangDTO kh = new KhachHangDTO();
                kh.MaKhachHang = maKhachHang;
                kh.HoTen = hoTen;
                kh.DiaChi = diaChi;
                kh.DienThoai = dienThoai;
                kh.Email = email;
                kh.TienNo = d_TienNo;
                kh.TinhTrang = 1;
                listCapNhat.Add(kh);
            }


            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                int maKhachHang = (int)dtXoa.Rows[i]["MaKhachHang"];
                KhachHangService.Delete(maKhachHang);
            }

            foreach (KhachHangDTO kh in listThem)
                KhachHangService.Insert(kh);
            foreach (KhachHangDTO kh in listCapNhat)
                KhachHangService.Update(kh);
            save = false;
            btnCapNhat.Enabled = false;
            dgvKhachHang.ReadOnly = true;
            return true;
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            if(CapNhat())
                MessageBoxEx.Show("Đã cập nhât!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBoxEx.Show("Không thể cập nhât!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void frmQuanLyKhachHang_FormClosing(object sender, FormClosingEventArgs e)
        {
           
            if (save && btnCapNhat.Enabled)
            {
                DialogResult diagSave = MessageBoxEx.Show("Bạn có muốn lưu?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (diagSave == DialogResult.Yes)
                {
                    if (!CapNhat())
                    {
                        e.Cancel = true;
                        MessageBoxEx.Show("Không thể cập nhât!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        isFormClosing = false;
                    }
                }
                if (diagSave == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    isFormClosing = false;
                }


            }
        }

        private void dgvKhachHang_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            save = true;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadGridView();
        }
    }
}